﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.ServiceModel;
using System.Text;

namespace CalService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CalendarService" in code, svc and config file together.
    public class CalendarService : ICalendarService
    {
        DalServiceRef.IDalService sr = new DalServiceRef.DalServiceClient();

        /*** Login service returns a populated User object if login valid ***/
        public Model.User Login(string Username, string Password)
        {
            Model.User user = new Model.User(Username, Password);

            if (user.PKID > 0) // user exists in db
            {
                return user;
            }
            else // user doesn't exist in db
            {
                return null;
            }

            //dalUser = sr.Login(Username, Password);

            //calUser.Username = dalUser.Username;


            //return calUser;
        }

        public void Register(string Username, string Password)
        {
            byte[] salt = GenerateSalt(10);
            byte[] hash = GenerateHash(Password, salt);

            sr.Register(Username, salt, hash);
        }

        private static byte[] GenerateSalt(int size)
        {
            //Generate a cryptographic random number
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] salt = new byte[size];
            rng.GetBytes(salt);

            //Return a Base64 string representation of the random number.
            return salt;
        }

        private static byte[] GenerateHash(string password, byte[] salt)
        {
            //return GenerateHash(Encoding.UTF8.GetBytes(password), salt);
            byte[] pwd = Encoding.UTF8.GetBytes(password);
            var saltedPassword = new byte[password.Length + salt.Length];
            pwd.CopyTo(saltedPassword, 0);
            salt.CopyTo(saltedPassword, password.Length);

            return new SHA256Managed().ComputeHash(saltedPassword);
        }
    }
}
